package com.example.statistics.ui.purchase

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.ClearanceBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.common.MultiSelectListActivity
import com.example.statistics.ex.httpGet
import com.example.statistics.ex.sumEx
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.google.gson.Gson
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.itemdecoration.LineItemDecoration
import com.example.statistics.ex.contentText
import com.example.statistics.ex.rotate
import kotlinx.android.synthetic.main.activity_clearance_fee_edit.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick


/**
 * 清关费用更新
 */
class ClearanceFeeEditActivity : BaseActivity() {

    var adapter: SlimAdapter? = null
    var isRefresh = false

    override val title: String
        get() = "清关费用"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_clearance_fee_edit)
        adapter()
        val purchaseId = intent.getIntExtra(Constants.PURCHASE_PRODUCT_ID, -1)
        var dataList = (intent.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>)?.toMutableList()
        adapter?.setDataList(dataList.orEmpty())
        tv_value.contentText = dataList?.sumEx { it.value }.toString()


        topBarRightText("保存") {
            val list = originalData()
            val str = Gson().toJson(list.map { NameValue(it.id, it.name, it.value) })
            httpGet<PurchaseProductBean>(UrlConfig.PURCHASE_CLEARANCE_UPDATE, config = {
                isShowDialog = true
                listParams = listOf("clearance" to str, "id" to purchaseId)
            }) {
                activityFinish(Constants.DATA to list)
            }
        }

        iv_refresh.onClick {
            isRefresh = false
            iv_refresh.rotate {
                iv_refresh.visibility = View.GONE
                tv_value.contentText = originalData().sumEx { it.value }.toString()
            }
        }

        layout_add.onClick {
            val originalList = originalData()
            activityForResult<MultiSelectListActivity>(
                    Constants.TITLE to title,
                    Constants.TYPE to ClearanceBean::class.java,
                    Constants.PATH to UrlConfig.PURCHASE_CLEARANCE_FIELD_LIST,
                    Constants.DATA to dataList?.map { it.id }
            ) {
                dataList = (it?.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>)?.toMutableList()
                val resultDataList = mutableListOf<ClearanceBean>()
                dataList?.forEach out@{ newData ->
                    originalList.forEach { originalData ->
                        if (newData.name == originalData.name) {
                            newData.value = originalData.value
                            resultDataList.add(newData)
                            return@out
                        }
                    }
                    resultDataList.add(newData)
                }
                adapter?.setDataList(resultDataList)
            }
        }
    }


    private fun adapter() {
        recycler_view_clearance.addItemDecoration(LineItemDecoration())
        adapter = SlimAdapter.creator()
                .register<ClearanceBean>(R.layout.list_item_clearance_fee_edit) { injector, bean, position ->
                    injector.text(R.id.tv_name, bean.name)
                            .text(R.id.et_value, bean.value.toString())
                            .tag(R.id.tv_name, bean.id)
                            .with<EditText>(R.id.et_value) {
                                it.addTextChangedListener(object : TextWatcher {
                                    override fun afterTextChanged(p0: Editable?) {
                                        if (!isRefresh) {
                                            iv_refresh.visibility = View.VISIBLE
                                            isRefresh = true
                                        }
                                    }

                                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                                    }

                                    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                                    }
                                })
                            }

                }
                .attachTo(recycler_view_clearance)

    }


    private fun originalData(): MutableList<ClearanceBean> {
        val originalList = mutableListOf<ClearanceBean>()
        for (i in 0 until recycler_view_clearance.childCount) {
            val view = recycler_view_clearance.getChildAt(i)
            val field = view.find<TextView>(R.id.tv_name)
            val editText = view.find<EditText>(R.id.et_value)
            val clearanceBean = ClearanceBean(
                    id = field.tag.toString().toInt(),
                    name = field.text.toString(),
                    value = if (editText.text.isNullOrBlank()) 0.0 else editText.text.toString().toDouble()
            )
            originalList.add(clearanceBean)
        }
        return originalList
    }

    class NameValue(val id: Int, var name: String, var value: Double)
}